<template>
  <div>
  	<a-image v-if="_d.isImg"
      :width="200"
      :style="{ display: 'none' }"
      :preview="{
        visible: _d.visible,
        onVisibleChange: (val) => _d.visible = val,
      }"
      :src="_d.filePath"
    />
    <a-modal v-else
      v-model:visible="_d.visible"
      title="预览文件"
      width="100%"
      wrap-class-name="m-file-preview-modal"
      :footer="null"
      :bodyStyle="{padding: 0}">
      <iframe class="filename" :src="_d.filePath" frameborder='1'></iframe>
    </a-modal>
  </div>
</template>

<script setup>
	import { reactive, ref, computed, onMounted } from 'vue'
	import { notification } from 'ant-design-vue';
	import {downFileUrl} from "@/api/file.js";
	import {instance} from "@/api/request.js";

	const _d = reactive({
		visible: false,

		filePath: '', // 文件路径,
		isImg: false,
	})

	onMounted(() => {
	
	})

	function show(id) {
		let params = {
			fileId: id
		}
		instance({
	    url: downFileUrl,
	    method: 'post',
	    data: params,
	    responseType: 'blob',
	  }).then(res => {
	  	// 抛出异常，并直接结束当前函数
		  if(res.data.size == 0) {
		    notification.error({
		    	message: '提示',
		    	description: '查看附件失败'
		    })
		    return;
		  }

	  	try {
				let contentDisposition = res.headers['content-disposition'].split('.');
				let fileType = contentDisposition[contentDisposition.length - 1];
				// 类型判断
				if(fileType == 'pdf') {
					var blob = new Blob([res.data], { type: 'application/pdf' });
    			var href = window.URL.createObjectURL(blob);
    			_d.isImg = false;
    			_d.filePath = href;
					_d.visible = true;
					return;
				} else {
					let blob = new Blob([res.data])
				  let href = window.URL.createObjectURL(blob); //创建链接
				
				  // 是否为图片
				  _d.isImg = ['jpg', 'jpeg', 'png'].includes(fileType);
				  if(_d.isImg) {
				  	_d.filePath = href;
						_d.visible = true;
						return;
				  } else {
				  	// 这儿也许可以下载
				  	window.open(href);
				  }
				}
			} catch(err) {
				console.log(err);
			}
	  })
	}

	// 判断是否为图片

	defineExpose({
		show
	})

</script>

<style lang="less">
.m-file-preview-modal {
	.ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  	
  	.filename {
  		display: block;
			margin: 0 auto;
			width: 100%;
			height: 100%;
			border: none;
  	}
  }
}
</style>